﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Requests;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.Plugins;
using System.Net.Mail;
using System.Net;

namespace MethodWorx.CMS.Workflow.SendEmail
{
    public class SendEmailWorkflowComponent : WorkflowComponent<SendEmailConfigurationController>
    {
        public SendEmailWorkflowComponent(Plugin plugin)
            : base(plugin)
        {
        }

        public static Guid ComponentId = Guid.Parse("{123E0CD5-5AEC-4E31-9D02-3896CBFBB4F7}");

        public override Guid Id
        {
            get { return ComponentId;  }
        }

        public override string Category
        {
            get { return "Utility";  }
        }

        public override string Name
        {
            get { return "Send Email";  }
        }

        public override string Description
        {
            get { return "Sends an email";  }
        }

        public override string View
        {
            get { return "SendEmailConfigurationView.ascx";  }
        }

        public override StepExecutionResult Execute(IWorkflowExecutionContext context, IWorkflowConfiguration configuration)
        {
            //
            //  ok, here we go..
            var config = configuration as SendEmailConfiguration;

            if(config != null)
            {
                var smtp = new SmtpClient(config.SmtpHost);
                smtp.Credentials = new NetworkCredential(config.SmtpUsername, config.SmtpPassword);
                var message = new MailMessage();

                message.To.Add(this.ParseString(config.To, context.GetAllWorkflowValues()));
                message.From = new MailAddress(this.ParseString(config.From, context.GetAllWorkflowValues()));
                message.Subject = this.ParseString(config.Subject, context.GetAllWorkflowValues());
                message.Body = this.ParseString(config.Message, context.GetAllWorkflowValues());

                smtp.Send(message);

                //  return the created item
                return StepExecutionResult.Ok();

            }
            else
                return StepExecutionResult.Error("Unexpected Workflow Error, invalid configuration");
        }
    }
}
